<script setup lang="ts">
import { computed, ref, onMounted, reactive } from 'vue'
import { getUserListApi, userDeleteApi, editUserApi } from '@/api/user'
import { baseURL } from '@/utils/request'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import UploadComponent from '@/components/upload/UploadComponent.vue'

interface User {
    [key: string]: any
    username: string
    role: number
    gender: string
    introduction: string
    avatar: string
}

// 搜索
const search = ref('')
const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !search.value ||
            data.username.toLowerCase().includes(search.value.toLowerCase())
    )
)

// 获取列表

let loading = ref(true)

let tableData = ref<User[]>([])

const getUserList = async () => {
    const res = await getUserListApi()
    tableData.value = res.data.data;
}

const getAvatar = (user: User) => {
    return user.avatar.includes('http') ? user.avatar : `${baseURL}/${user.avatar}`
}

onMounted(async () => {
    await getUserList()
    loading.value = false
})


// 删除
const confirmDelete = async (index: number, row: User) => {
    const result = await userDeleteApi(row._id)
    ElMessage({
        type: 'success',
        message: result.data.msg
    })
    await getUserList()
}


// 编辑
interface UserForm {
    [key: string]: any
    username: string
    password: string
    role: number
    introduction: string
    avatar: string
    gender: number
    file: Object
}

let userForm: UserForm = reactive(
    {
        username: '',
        password: '',
        role: 0,
        introduction: '暂无简介',
        avatar: '',
        gender: 0,
        file: {}
    }
)
let dialogFormVisible = ref(false)

const handleEdit = (index: number, row: UserForm) => {
    dialogFormVisible.value = true
    console.log("row");
    console.log(row);

    userForm = row
    userForm.file = {}
}

const ruleFormRef = ref<FormInstance>()

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 8, message: '长度范围为 3 到 8 个字符', trigger: 'blur' },
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '请输入个人简介', trigger: 'blur' },
        { min: 0, max: 50, message: '最大为 50 个字符', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 12, message: '长度范围为 5 到 12 个字符', trigger: 'blur' },
    ],
    role: [
        { required: true, message: '请选择权限', trigger: 'blur' },
    ],
})

const handleChange = (file: File) => {
    userForm.avatar = URL.createObjectURL(file)
    userForm.file = file
}

const onSubmit = async () => {
    ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
            const params = new FormData()
            for (const i in userForm) {
                params.append(i, userForm[i])
            }
            console.log("userForm");
            console.log(userForm);

            const res = await editUserApi(params)
            ElMessage({
                type: 'success',
                message: res.data.msg
            })
            await getUserList()
            dialogFormVisible.value = false
        }
    })
}

const cancelChange = () => {
    dialogFormVisible.value = false
    userForm = {
        username: '',
        password: '',
        role: 0,
        introduction: '暂无简介',
        avatar: '',
        gender: 0,
        file: {}
    }
}
</script>

<template>
    <div id="userList">
            <el-table v-loading="loading" :data="filterTableData" style="width: 100%" max-height="800px" stripe>
                <el-table-column label="用户名" prop="username" />
                <el-table-column label="头像" prop="avatar">
                    <template #default="scope">
                        <img class="avatarImg" :src="getAvatar(scope.row)">
                    </template>
                </el-table-column>
                <el-table-column label="性别" prop="gender">
                    <template #default="scope">
                        {{ scope.row.gender === 1 ? '男' : (scope.row.gender === 2 ? '女' : '未知') }}
                    </template>
                </el-table-column>
                <el-table-column label="个人简介" prop="introduction" />

                <el-table-column label="权限" prop="role">
                    <template #default="scope">
                        <el-tag class="ml-2" :type="scope.row.role === 0 ? 'info' : 'success'">
                            {{ scope.row.role === 0 ? '编辑' : '管理员' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="right">
                    <template #header>
                        <el-input v-model="search" size="large" placeholder="搜索用户名~" />
                    </template>
                    <template #default="scope">
                        <el-button :disabled="scope.row.role === 1" size="small"
                            @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                        <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled"
                            icon-color="rgb(242, 111, 109)" title="确认删除?" @confirm="confirmDelete(scope.$index, scope.row)">
                            <template #reference>
                                <el-button size="small" type="danger">删除</el-button>
                            </template>
                        </el-popconfirm>

                    </template>
                </el-table-column>
            </el-table>

            <el-dialog v-model="dialogFormVisible" title="修改用户" top="8vh">
                <el-form class="editForm" ref="ruleFormRef" :model="userForm" label-width="auto" label-position="left"
                    size="large" :rules="rules">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userForm.username" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="userForm.password" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="userForm.gender" placeholder="请选择性别">
                            <el-option label="男" :value="1" />
                            <el-option label="女" :value="2" />
                            <el-option label="未知" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="权限" prop="role">
                        <el-select v-model="userForm.role" placeholder="请选择权限">
                            <el-option label="管理员" :value="1" />
                            <el-option label="编辑" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="userForm.gender" placeholder="请选择性别">
                            <el-option label="男" :value="1" />
                            <el-option label="女" :value="2" />
                            <el-option label="未知" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="个人简介" prop="introduction">
                        <el-input v-model="userForm.introduction" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" />
                    </el-form-item>
                    <el-form-item label="头像" prop="avatar">
                        <UploadComponent :avatar="userForm.avatar" @fileChange="handleChange" />
                    </el-form-item>
                    <el-form-item>
                        <div class="buttonBar">
                            <el-button class="submitBtn" type="primary" @click="onSubmit">修改</el-button>
                            <el-button class="submitBtn" @click="cancelChange">取消</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-dialog>
    </div>
</template>

<style lang='less' scoped>
#userList {
    .avatarImg {
        border-radius: 50%;
        border: 1px solid #666;
        width: 50px;
        height: 50px;
        object-fit: cover;
    }

    .editForm {
        margin: 0 50px;

        .el-input,
        .el-select {
            width: 50%;
        }

        .el-textarea {
            width: 90%;
        }

        .upload-demo {
            width: 50%;
        }

        .buttonBar {
            display: flex;
            justify-content: space-around;
            width: 100%;

            .el-button {
                width: 45%;
            }
        }
    }

}
</style>